package com.sunday.electric.http;

import com.sunday.common.utils.EncryptUtils;
import com.sunday.common.utils.StringUtils;
import com.sunday.electric.utils.GsonConverterFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2016/1/26.
 */
public class ApiClient {
    private static  Retrofit  imAdapter;
    private static  IMService imService;
    private static String API_URL = "http://www.bbaba.com";
    private static OkHttpClient client ;
    public static IMService getIMAdapter(){
        if(imAdapter==null){
            client = new OkHttpClient.Builder()
                    .readTimeout(6000, TimeUnit.SECONDS)
                    .retryOnConnectionFailure(true)
                    .addInterceptor(new SignInterceptor())
                    .build();
            imAdapter = new Retrofit.Builder()
                    .baseUrl(API_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .client(client)
                    .build();
            imService = imAdapter.create(IMService.class);
        }
        return imService;
    }

    private static String sign(String nonce,String timestamp){
        StringBuilder sb = new StringBuilder();
        sb.append("wBH4YJUYIa6a").append(nonce).append(timestamp);
        return EncryptUtils.sha1(sb.toString());

    }

    private static class SignInterceptor implements Interceptor{

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
              /*      if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
                        return chain.proceed(originalRequest);
                    }*/
            String nonce = StringUtils.getRandomString(8);
            String timestamp = String.valueOf(System.currentTimeMillis()/1000);
            Request compressedRequest = originalRequest.newBuilder()
                    .header("App-Key", "uwd1c0sxdoyn1")
                    .header("Nonce", nonce)
                    .header("Timestamp",timestamp)
                    .addHeader("Signature",sign(nonce,timestamp))
                    .method(originalRequest.method(),originalRequest.body())
                    .build();
            Response response = chain.proceed(compressedRequest);
            return response;
        }
    }

}
